<template>
  <div class="model">
    <div class="mask" @click="changeisShowlogin(false)"></div>
    <div class="loginbox">
      <div class="close" @click="changeisShowlogin(false)"></div>
      <!-- 导航 -->
      <nav class="nav">
        <a
          href="#"
          :class="{ active: isShowPhoneLogin }"
          @click="isShowPhoneLogin = true"
          >手机号登录</a
        >
        |

        <a href="#" :class="{ active: !isShowPhoneLogin }" @click="showQr"
          >微信扫码登录</a
        >
      </nav>
      <!-- 导航对应的内容区 -->
      <div class="content">
        <!-- 手机号登录 -->
        <div class="phoneLogin" v-show="isShowPhoneLogin">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="imgs"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              v-model="yzmCode"
            />
            <button class="btn btncode" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btn btncode" v-show="isShowCount">
              {{ count + "s" }}
            </button>
          </div>
          <div class="row">
            <button class="btn btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信扫码登录 -->
        <!-- 显示微信二维码第二步:提供显示二维码容器的ID -->
        <div class="qrLogin" v-show="!isShowPhoneLogin" id="weixin">
          微信扫码登录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { DengLyanzAPI, PhoneReginAPI, BindingAPI } from "../request/api";
import { validdatephoneNumber } from "../utils/index";
export default {
  methods: {
    //导入仓库方法修改仓管state值
    ...mapMutations({
      changeisShowlogin: "showmodal/changeisShowlogin",
      changeislogin: "islogins/changeislogin",
      changeistoast: "istoasts/changeistoast",
    }),
    ...mapActions({
      asyncshowtoast: "istoasts/asyncshowtoast",
      asyncchangeUser:"user/asyncchangeUser"
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    //统一校验手机号和滑块验证码
    toVerify() {
      //1.使用正则判断手机号是否输入正确,不正确提示
      if (!validdatephoneNumber(this.phoneNumber)) {
        this.asyncshowtoast({
          istoast: true,
          title: "请输入正确的手机号码",
          type: "danger",
        });
        return;
      }
      //2.判断滑块验证码 是否输入正确,不正确,提示
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        this.asyncshowtoast({
          istoast: true,
          title: "请重新滑动滑块验证码",
          type: "danger",
        });
        return;
      }
      return true;
    },
    //登录方法
    async submitFn() {
      //1.2调用toVerify进行校验,如果通过了,继续判断3,否则return 不执行3
      if (!this.toVerify()) return;
      //3.判断短信验证码是否正确.
      if (this.yzmCode == "") {
        this.asyncshowtoast({
          istoast: true,
          title: "请输入正确的验证码",
          type: "danger",
        });
        return;
      }
      //4.发起登录请求
      let res = null;
      let uuid = localStorage.getItem("uuid");
      if (uuid) {
        //如果有uuid则式手机绑定微信 登录请求
        res = await BindingAPI({
          verifyCode: this.yzmCode,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        //如果没有uuid 依然是普通的手机号码验证码登录请求
        res = await PhoneReginAPI({
          verifyCode: this.yzmCode,
          phone: this.phoneNumber,
        });
      }
      if (!res) return;
      if (res.code == 0) {
        //1.提示登录成功
        this.asyncshowtoast({
          istoast: true,
          title: "登录成功",
          type: "success",
        });
        //2.存储token,后面发请求时需要用到,localStorage setItem() getItem()
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        //3.隐藏登录框
        this.changeisShowlogin(false);
        //4.更新登录状态(已登录显示 购物车按钮,未登录显示,登录按钮)
        this.changeislogin(true);
        //5.清除uuid(用过)
        localStorage.removeItem("uuid");   
        //登录成功后调用actions更新用户信息
          this.asyncchangeUser()
      }
    },
    //手机登录验证
    async getCode() {
      //1.2调用toVerify进行校验,如果通过了,继续判断3,否则return 不执行3
      if (!this.toVerify()) return;
      //3.开始获取验证码(请求后台发送验证码),发送成功后,进行倒计时功能
      let res = await DengLyanzAPI({ phone: this.phoneNumber });
      //拦截器已经报错了,也就是没有必要再判断==0情况
      if (!res) return;
      //成功的场景
      if (res.code == 0) {
        this.isShowCount = true;
        let timer = setInterval(() => {
          this.count--;
          if (this.count == 0) {
            //停止定时器
            clearInterval(timer);
            this.count = 5;
            this.isShowCount = false;
          }
        }, 1000);
      }
    },
    //显示二维码fn
    showQr() {
      this.isShowPhoneLogin = false;
      //显示微信二维码第三步:实例化wxlogin
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5xckxvZ2luIHsNCiAgICB0ZXh0LWFsaWduOiBjZW50ZXI7DQp9",
      });
    },
  },
  data() {
    return {
      // 是否显示手机号登录
      isShowPhoneLogin: true,
      msg: "向右滑动",
      // 滑块背景图数组
      imgs: [
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
      ],
      phoneNumber: "",
      count: 5,
      isShowCount: false,
      //获取验证码
      yzmCode: "",
    };
  },
};
</script>

<style lang="less" scoped>
.model {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    position: absolute;
    bottom: 0;
    top: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      top: 15px;
      right: 60px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
    }
  }
  .nav {
    margin-top: 45px;
    text-align: center;
    a {
      color: rgb(0, 0, 0);
      text-decoration: none;
      &.active {
        color: blue;
      }
    }
  }
  .content {
    margin: 20px auto 0;
    width: 355px;
    .qrLogin {
      text-align: center;
    }
    .phoneLogin {
      .row {
        display: flex;
        margin-bottom: 20px;
        input {
          flex: 1;
          height: 50px;
          text-indent: 1em;
          outline-style: none;
        }
        .btn {
          background-color: #0a328e;
          color: #fff;
          border: none;
        }
        .btncode {
          margin-left: 10px;
          width: 80px;
        }
        .btnlogin {
          height: 50px;
          flex: 1;
        }
      }
    }
  }
}
// 修改子组件滑块样式
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  .slide-verify-slider {
    margin-top: 0;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>